import { getMongoRepository } from 'typeorm';
import { Notices } from '../models/Notices';

class NoticesService {

  // 根据id查询
  findById(id: string) {
    const noticesRepository = getMongoRepository(Notices)
    return noticesRepository.findOne(id)
  }

  // 根据接收者或者所有人获取最新一条公告
  findBySubscriber(subscriber: number) {
    const noticesRepository = getMongoRepository(Notices)
    return noticesRepository.findOne({
      where: {
        $or: [
          { subscriber: subscriber },
          { subscriber: '3' }
        ]
      },
      order: { _id: -1 }
    })
  }

  // 创建公告
  save(notices: Notices) {
    const noticesRepository = getMongoRepository(Notices)
    return noticesRepository.save(notices)
  }

  // 根据发布者+标题（模糊匹配）和接收者查询
  findByNameKeyAndSubscriber(label: string, value: string, subscriber: number, skipNum: number, limit: number) {
    const noticesRepository = getMongoRepository(Notices)
    return noticesRepository.find({
      where: {
        [label]: { $regex: value },
        subscriber: { $regex: subscriber }
      },
      skip: skipNum,
      take: limit,
      // 倒序（降序）
      order: { _id: 'DESC' }
    })
  }

  // 根据发布者+标题（模糊匹配）和接收者查询总数量
  async findByNameKeyAndSubscriberCount(label: string, value: string, subscriber: number) {
    const noticesRepository = getMongoRepository(Notices);
    const [users, count] = await noticesRepository.findAndCount({
      where: {
        [label]: { $regex: value },
        subscriber: { $regex: subscriber }
      }
    })
    return count
  }

  // 删除
  deleteById(id: string) {
    const noticesRepository = getMongoRepository(Notices)
    return noticesRepository.delete(id)
  }

  // 获取用户的公告，（例如：教师角色的所有可查看的公告）
  // 根据发布者+标题（模糊匹配）进行查询
  findRoleNotice(label: string, value: string, subscriber: number, skipNum: number, limit: number) {
    const noticesRepository = getMongoRepository(Notices)
    return noticesRepository.find({
      where: {
        [label]: { $regex: value },
        $or: [
          { subscriber: { $regex: subscriber } },
          { subscriber: '3' }
        ]
      },
      skip: skipNum,
      take: limit,
      // 倒序（降序）
      order: { _id: 'DESC' }
    })
  }

  // 根据发布者+标题（模糊匹配）进行查询总数量
  async findRoleNoticeCount(label: string, value: string, subscriber: number) {
    const noticesRepository = getMongoRepository(Notices);
    const [users, count] = await noticesRepository.findAndCount({
      where: {
        [label]: { $regex: value },
        $or: [
          { subscriber: { $regex: subscriber } },
          { subscriber: '3' }
        ]
      },
    })
    return count
  }

}

export default new NoticesService()